/*
 * Project Name spring-boot-tools
 * File Name Action101
 * Package Name com.huxiaosu.tools.mina.action
 * Create Time 2024/5/25
 * Create by name：liujie
 */
package com.huxiaosu.tools.mina.action;

import com.alibaba.fastjson2.JSONObject;
import com.huxiaosu.tools.mina.cache.SessionUsers;
import com.huxiaosu.tools.mina.utils.Constants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/25 14:45
 */
@Slf4j
@Component
public class Action102 extends AbstractMessageAction {
    @Override
    public byte getMessageCommandId() {
        return Constants.T102;
    }

    @Override
    public String getMessageCommandName() {
        return "Register";
    }

    @Override
    @SneakyThrows(value = Throwable.class)
    public void execute() {
        log.info("<客户端注册请求>");
        String userInfo = new String(message.getBody());
        JSONObject userJson = JSONObject.parseObject(userInfo);
        String userId = userJson.getString("userId");
        String sessionId = userJson.getString("sessionId");
        log.info("<userId = {} ,  sessionId =  {}>",userId,sessionId);
        cacheService.put(userId,sessionId);
        Set<String> sessionIds = (Set<String>) cacheService.get(userId);
        Set<String> newSessionSet = new HashSet<>();
        sessionIds.forEach(item->{
            IoSession userSession = (IoSession) SessionUsers.getInstance().getSession(item);
            if(userSession == null || userSession.isClosing()){
                SessionUsers.getInstance().clearSession(item);
            }else{
                newSessionSet.add(item);
            }
        });
        //
        cacheService.put(userId,newSessionSet);
        SessionUsers.getInstance().addUserSession(sessionId, session);
        JSONObject result = new JSONObject();
        result.put("status", Constants.SUCCESS);
        result.put("result", "register user success");

        message.setBody(result.toString().getBytes(Constants.CHARSET));
        message.setBodyLength(result.toString().getBytes(Constants.CHARSET).length);
        log.info("response info{}",result.toJSONString());
        session.write(message.toByte());

    }
}
